package com.android.accessibility.function;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.android.accessibility.utils.Log;
import com.android.accessibility.utils.Utils;

public class NearByFriendsAccessibility extends Accessibility {
    private static final CharSequence NearbyFriendsUI = "com.tencent.mm.plugin.nearby.ui.NearbyFriendsUI";
    private static final CharSequence ContactInfoUI = "com.tencent.mm.plugin.profile.ui.ContactInfoUI";
    private static final CharSequence SayHiEditUI = "com.tencent.mm.ui.contact.SayHiEditUI";
    private static final CharSequence BindMContactIntroUI = "com.tencent.mm.ui.bindmobile.BindMContactIntroUI";

    private boolean mComplete = false;
    private static final boolean ALLOW_CLICK = true;
    private CharSequence mNickName = null;

    private Queue<AccessibilityNodeInfo> mNearByList;

    public NearByFriendsAccessibility(AccessibilityService service) {
        super(service);
    }

    private CharSequence getSayHiEditUI() {
        int verCode = Utils.getVersionCode(getService(), "com.tencent.mm");
        Log.d(Log.TAG, "Wechat verCode : " + verCode);
        return null;
    }

    public void onAccessibilityEvent(AccessibilityEvent event) {
        int eventType = event.getEventType();
        if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            if (NearbyFriendsUI.equals(mClassName)) {
                performClick();
            } else if (BindMContactIntroUI.equals(mClassName)) {
                clickBack();
            } else if (ContactInfoUI.equals(mClassName)) {
                if (mComplete) {
                    clickBack();
                } else {
                    clickSayHello();
                }
            } else if (SayHiEditUI.equals(mClassName)) {
                if (mComplete) {
                    clickBack();
                } else {
                    paste();
                    clickSendButton();
                    mComplete = true;
                }
            }
        } else if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
            if (NearbyFriendsUI.equals(mClassName)) {
                init();
                performClick();
            }
        } else if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
            if (SayHiEditUI.equals(mClassName)) {
                clickBack();
            }
        }
    }

    private void init() {
        fetchNearByList();
    }

    private void clean() {
        mNearByList = null;
    }

    private void fetchNearByList() {
        Log.d(Log.TAG, "");
        if (mNearByList == null) {
            mNearByList = new LinkedBlockingQueue<AccessibilityNodeInfo>();
        }
        List<AccessibilityNodeInfo> list = getListItem();
        mNearByList.addAll(list);
    }

    private void performClick() {
        if (!ALLOW_CLICK) {
            return;
        }
        if (mNearByList == null) {
            return;
        }
        AccessibilityNodeInfo nodeInfo = mNearByList.poll();
        if (nodeInfo != null) {
            mComplete = false;
            mNickName = findNickName(nodeInfo);
            ClipboardManager clipboard = (ClipboardManager) getService().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("label", mNickName);
            clipboard.setPrimaryClip(clip);
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        } else {
            checkScroll();
        }
    }

    private void checkScroll() {
        if (mNearByList != null && mNearByList.size() <= 0) {
            AccessibilityNodeInfo listNodeInfo = Helper.findViewNodeInfo(
                    getService().getRootInActiveWindow(), "android.widget.ListView");
            if (listNodeInfo != null) {
                listNodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
            }
        }
    }

    private List<AccessibilityNodeInfo> getListItem() {
        AccessibilityNodeInfo nodeInfo = Helper.findViewNodeInfo(getService()
                .getRootInActiveWindow(), "android.widget.ListView");
        List<AccessibilityNodeInfo> list = null;
        if (nodeInfo != null) {
            int count = nodeInfo.getChildCount();
            AccessibilityNodeInfo info = null;
            CharSequence nickName = null;
            list = new ArrayList<AccessibilityNodeInfo>();
            for (int index = 1; index < count; index++) {
                info = nodeInfo.getChild(index);
                nickName = findNickName(info);
                Log.d(Log.TAG, "nickName : " + nickName);
                if (nickName != null) {
                    if (list != null && info != null) {
                        list.add(info);
                    }
                }
            }
        }
        return list;
    }

    private CharSequence findNickName(AccessibilityNodeInfo info) {
        if (info == null) {
            return null;
        }
        String nickName = null;
        AccessibilityNodeInfo nickViewNode = findNickViewNode(info);
        if (nickViewNode != null) {
            nickName = String.valueOf(nickViewNode.getText());
        }
        return nickName;
    }

    private AccessibilityNodeInfo findNickViewNode(AccessibilityNodeInfo info) {
        if (info != null && info.getChildCount() > 0) {
            return info.getChild(0);
        }
        return null;
    }

    private void clickBack() {
        Log.d(Log.TAG, "");
        getService().performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
    }

    private void clickSayHello() {
        boolean result = Helper.findAndPerformAction(getService(), "打招呼");
        Log.d(Log.TAG, "result : " + result);
        if (!result) {
            clickBack();
        }
    }

    private void clickSendButton() {
        Log.d(Log.TAG, "");
        // Helper.findAndPerformAction(getService(), "发送");
        clickBack();
    }

    @SuppressLint("InlinedApi")
    private void paste() {
        AccessibilityNodeInfo nodeInfo = getService().getRootInActiveWindow();
        AccessibilityNodeInfo info = Helper.findViewNodeInfo(nodeInfo, "android.widget.EditText");
        Log.d(Log.TAG, "info : " + info);
        if (info != null) {
            try {
                info.setText(mNickName);
            } catch(Exception e) {
            }
        }
    }

    @Override
    public void start() {
        init();
        performClick();
    }

    @Override
    public void stop() {
        clean();
    }
}
